package cn.xunjie.ymcc.service.impl;

import cn.xunjie.ymcc.domain.CourseType;
import cn.xunjie.ymcc.dto.CrumbsDto;
import cn.xunjie.ymcc.mapper.CourseTypeMapper;
import cn.xunjie.ymcc.result.JSONResult;
import cn.xunjie.ymcc.service.ICourseTypeService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author xue.jiao
 * @since 2022-07-20
 */
@Slf4j
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Override
    @Cacheable(cacheNames="courseDate",key="'Tree'")//courseDate::Tree
    public List<CourseType> treeData() {
       /* String courseDateTree = "coursedatetree";
        Object obj = redisTemplate.opsForValue().get("courseDateTree");
        if(obj != null){
            log.info("走redis");
            return (List<CourseType>)obj;
        }
        log.info("走mysql");*/
        List<CourseType> tree = tree();
        /*redisTemplate.opsForValue().set("courseDateTree",tree);*/
        return tree;


    }

    @Override
    public JSONResult crumbs(Long courseTypeId) {
        List<CrumbsDto> crumbsDtos = new ArrayList<>();
        CourseType courseType = courseTypeMapper.selectById(courseTypeId);
        String[] split = courseType.getPath().split("\\.");
        List<CourseType> courseTypes = courseTypeMapper.selectBatchIds(Arrays.asList(split));
        for (CourseType type : courseTypes) {
            CrumbsDto crumbsDto = new CrumbsDto();
            crumbsDto.setOwnerProductType(type);
            EntityWrapper<CourseType> wrapper = new EntityWrapper<>();
            wrapper.eq("pid",type.getPid())
            .ne("id",type.getId());
            List<CourseType> types = courseTypeMapper.selectList(wrapper);
            crumbsDto.setOtherProductTypes(types);
            crumbsDtos.add(crumbsDto);

        }
        return JSONResult.success(crumbsDtos);
    }

    private List<CourseType> tree() {
        log.info("走mysql");
        List<CourseType> courseTypes = selectList(null);

        //为了后面找自己的父亲，我们这里可以把整体的部门数据，转换一份成Map<id,menu>
        Map<Long, CourseType> allCourses = courseTypes.stream().collect(Collectors.toMap(CourseType::getId, menu -> menu));
        List<CourseType> firstMenus = new ArrayList<>();//顶级部门
        for (CourseType course : courseTypes) {
            if(course.getPid() == null || course.getPid() == 0){
//        *    2.从所有数据中找出第一层级 firstMenus   我们需要返回的最外数据
                firstMenus.add(course);
            }else{
//        *    3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                CourseType parent = allCourses.get(course.getPid());
                if(parent != null){
                    parent.getChildren().add(course);
                }
            }
        }
        return firstMenus;
    }

    @Override
    @CacheEvict(cacheNames="courseDate", key = "'Tree'")
    public boolean deleteById(Serializable id) {
        boolean deleteById = super.deleteById(id);
        /*redisTemplate.delete("courseDateTree");*/
        return deleteById;
    }

    @Override
    @CacheEvict(cacheNames="courseDate", key = "'Tree'")
    public boolean updateById(CourseType entity) {
        boolean updateById = super.updateById(entity);
        /*redisTemplate.delete("courseDateTree");*/
        return updateById;
    }

    @Override
    @CacheEvict(cacheNames="courseDate", key = "'Tree'")
    public boolean insert(CourseType entity) {
        boolean insert = super.insert(entity);
        /*redisTemplate.delete("courseDateTree");*/
        return insert;
    }
}
